import request from "./request";
import {Message} from "element-ui";

const queryAllDictUrl = '/sys/dict/query/all'
const DICT_STORAGE_KEY = 'sys_dict'


const queryAllDict = function (callBack) {
    request({
        url: queryAllDictUrl,
        method: 'get',
    }).then(data => {
        let allDict = data.data
        callBack(allDict)
    }).catch(error => {
        callBack([])
    })
}
const setDictList = function (dictMap = {}) {
    const jsonStr = JSON.stringify(dictMap)
    sessionStorage.setItem(DICT_STORAGE_KEY, jsonStr)
}
const getDictMap = function () {
    const jsonStr = sessionStorage.getItem(DICT_STORAGE_KEY)
    if (jsonStr) return JSON.parse(jsonStr)
    return {}
}
const refreshSysDictCache = function (){
    queryAllDict(dictMap => {
        setDictList(dictMap)
        Message({
            message: "字典缓存刷新成功",
            type: 'success',
            duration: 5 * 1000
        })
    })
}
const loadSysDict = function () {
    const jsonStr = sessionStorage.getItem(DICT_STORAGE_KEY)
    if (jsonStr && jsonStr != '') return getDictMap()
    refreshSysDictCache()
}
/**
 * 获取字典标签
 * @param dictCode 字典代码
 * @param itemValue 键值
 * @constructor
 */
let CollectionLabel = function (dictCode, itemValue) {
    const dictMap = getDictMap()
    const dictItem = dictMap[dictCode].find(item => {
        return itemValue = item.itemValue
    })
    return dictItem ? dictItem.itemLabel : ""
}
let CollectionData = function (dictCode) {
    const dictMap = getDictMap()
    return dictMap ? dictMap[dictCode] : []
}
export default {
    install(Vue) {
        loadSysDict()
        window.CollectionLabel = CollectionLabel
        window.CollectionData = CollectionData
        window.refreshSysDictCache = refreshSysDictCache

        Vue.prototype.CollectionLabel = CollectionLabel
        Vue.prototype.CollectionData = CollectionData
        Vue.prototype.refreshSysDictCache = refreshSysDictCache
    }
}